/* Copyright (C) 2008  Romolo Camplani, Marco Fortunato, Marco Marelli, Guido Rota, Fabio A. Schreiber et al.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package org.dei.perla.sys.hlqexecutor;

import org.dei.perla.component.Startable;
import org.dei.perla.parser.datastructures.Stream;

/**
 * @author  Luigi Rinaldi
 */
public class Trigger implements Startable {

	private Thread triggerThread;
	/**
	 * @uml.property  name="stream"
	 * @uml.associationEnd  
	 */
	private Stream stream;
	private int samples;
	/**
	 * @uml.property  name="lastIDRecord"
	 */
	private int lastIDRecord;
	
	public Trigger(Stream stream, int samples){
		this.samples = samples;
		this.stream = stream;
		lastIDRecord = getLastIDRecord();  //inizializzo il valore dell'ultimo record inserito nella tabella 
	}
	
	/**
	 * @return
	 * @uml.property  name="lastIDRecord"
	 */
	private int getLastIDRecord(){
		//TODO fa una query per sapere qual è l'ultimo record inserito nello Stream
		return 0;
	}
	
	
	@Override
	public boolean isStarted() {
		return this.triggerThread.isAlive();
	}

	@Override
	public void start() {
		this.triggerThread.start();
		
	}

	@Override
	public void stop() {
		if(isStarted()){
			this.triggerThread.interrupt();
		}
		
	}
	
	/**
	 * 
	 * @author Luigi Rinaldi
	 *
	 */
	private class ThreadImplementation extends Thread {
		long timeInMillis;
		public ThreadImplementation(long timeInmillis) {
			this.timeInMillis = timeInMillis;
		}
		
		@Override
		public void run(){
			try{
				while(!triggerThread.isInterrupted()){
					//TODO fare polling su uno stream per vedere se sono stati aggiunti un tot di record
					Thread.sleep(timeInMillis);
				}
			}catch (InterruptedException e){
				e.printStackTrace();
			}
		}	
	}
}

